package com.xnew.utils;

import org.apache.commons.collections4.MapUtils;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.http.HttpStatus;

import javax.validation.ConstraintViolation;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author anonymous
 * @Date 2020/10/14
 */
public class DataOutput<T> implements Serializable {

    /**
     * 返回编码
     * 200成功，负数是失败，其他根据httpstatus码返回
     */
    private int code;

    /**
     * 返回信息描述
     */
    private String msg;

    /**
     * 总条数
     */
    private long recordsTotal;

    /**
     * 过滤条数
     */
    private long recordsFiltered;

    /**
     * 返回数据
     */
    private Object data;

    /**
     * 参数校验结果
     */
    private Map<String,String> validator;

    /**
     * 响应数据标识
     * */
    private String dataNo;

    public static DataOutput success(){
        DataOutput output = new DataOutput();
        output.setCode(HttpStatus.OK.value());
        output.setMsg("操作成功!");
        return output;
    }

    public static DataOutput fail(){
     DataOutput output = new DataOutput();
        output.setCode(-1);
        return output;
}

    public static DataOutput fail(Set<ConstraintViolation> validates){
        DataOutput output = new DataOutput();
        output.setCode(-1);
        return output;
    }

    public void validate(Set<ConstraintViolation> validates){
        if(MapUtils.isEmpty(this.getValidator())){
            this.setValidator(new HashMap<>());
        }
        for(ConstraintViolation validate : validates){
            PathImpl pathImpl = (PathImpl)validate.getPropertyPath();
            String name = pathImpl.getLeafNode().getName();
            String message = validate.getMessage();
            this.getValidator().put(name,message);
        }
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public long getRecordsTotal() {
        return recordsTotal;
    }

    public void setRecordsTotal(long recordsTotal) {
        this.recordsTotal = recordsTotal;
    }

    public long getRecordsFiltered() {
        return recordsFiltered;
    }

    public void setRecordsFiltered(long recordsFiltered) {
        this.recordsFiltered = recordsFiltered;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Map<String, String> getValidator() {
        return validator;
    }

    public void setValidator(Map<String, String> validator) {
        this.validator = validator;
    }

    public void setDataNo(String dataNo) {
        this.dataNo = dataNo;
    }
}
